<?php

namespace App\Http\Controllers\Admin;

use App\Common\Utils\EasyWechat;
use App\Http\Controllers\Controller;
use App\Models\AsyncExportTask;
use App\Models\Attachment;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpKernel\Exception\HttpException;

class AttachmentController extends Controller
{
    public function upload(Request $request)
    {
        $attachment = null;
        try {
            $requestFile = $request->file('attachment');

            // 上传微信素材
            $wxMedia = [];
            if ((int) $request->get('is_wechat_material', 2) === 1) { // 1: 是 2: 否
                $app = EasyWechat::getOfficialAccount();
                $localFilePath = storage_path('app') . DIRECTORY_SEPARATOR . Storage::disk('local')->putFile('temporary_material', $requestFile); // 先保存到本地才能上传
                $uploadRes = $app->material->uploadImage($localFilePath);
                Storage::disk('local')->delete($localFilePath);
                if (!isset($uploadRes['media_id'])) {
                    throw new HttpException(400, '上传素材发生错误:' . ($uploadRes['errmsg'] ?? ''));
                }
                $wxMedia = [
                    'wx_media_id' => $uploadRes['media_id'],
                    'wx_media_url' => $uploadRes['url'],
                    'wx_media_response' => $uploadRes,
                ];
            }

            // 上传 OSS
            $file = Storage::put('admin/' . Carbon::now()->format('Y-m-d'), $requestFile);

            $attachment = Attachment::create(array_merge(
                [
                    'url' => Storage::url($file),
                    'file' => $file,
                    'mime_type' => $requestFile->getMimeType()
                ],
                $wxMedia
            ));
        } catch (\Exception $e) {
            $this->response->errorBadRequest($e->getMessage());
        }

        return $this->response->created(null, $attachment);
    }

    /**
     * 下载异步导出文件
     * @param $id
     */
    public function downloadAsyncExportTask($id)
    {
        $task = AsyncExportTask::query()->with('attachments')->findOrFail($id);
        if ($task['status'] !== AsyncExportTask::STATUS_SUCCESS) {
            abort(400, '任务还没有完成');
        }

        return $this->response->array([
            'url' => Storage::exists($task['attachments'][0]['file']) ? Storage::url($task['attachments'][0]['file']) : ''
        ]);
    }

    /**
     * 异步导出任务列表
     * @return mixed
     */
    public function asyncExportTaskList()
    {
        return $this->response->array(AsyncExportTask::query()->with('operator')->where('operator_id', $this->user()->getAuthIdentifier())->paginate());
    }
}
